package cn.com.headfree.welfare.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.com.headfree.base.controller.ExBaseController;
import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.welfare.entity.FlPtr;
import cn.com.headfree.welfare.entity.FlPtr;
import cn.com.headfree.welfare.entity.Vo.PTRVo;
import cn.com.headfree.welfare.entity.Vo.XztxVo;
import cn.com.headfree.welfare.service.FlPtrService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 调动统计
 *
 * @author makejava
 * @since 2021-12-29 18:18:27
 */
@RestController
@RequestMapping("flPtr")
public class FlPtrController extends ExBaseController {
    private static final Logger LOG = LogManager.getLogger(ExBaseController.class);
    /**
     * 服务对象
     */
    @Resource
    private FlPtrService flPtrService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public ResultData selectOne(Integer id, HttpServletRequest request) {
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            FlPtr flPtr=this.flPtrService.queryById(id);
            if(flPtr!=null)
            {
                result.setSuccess(true);
                result.setData(flPtr);
            }else {
                result.setSuccess(false);
                result.setErrorMsg("查询失败");
            }


        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }

    /**
     * 新增数据
     *
     * @param flPtr 实例对象
     * @return 实例对象
     */
    @PostMapping("insert")
    public ResultData insert(@RequestBody FlPtr flPtr, HttpServletRequest request) {
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            flPtr.setOrgId(user.getBaseOrgId());
            flPtr.setCreaterId(user.getId());
            flPtr.setCreaterName(user.getName());
            flPtr.setCreateTime(new Date());
            flPtr.setDelSign(0);
            flPtr=this.flPtrService.insert(flPtr);
            if(flPtr!=null)
            {
                result.setSuccess(true);
                result.setData(flPtr);
            }else {
                result.setSuccess(false);
                result.setErrorMsg("添加失败");
            }


        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }

    /**
     * 修改数据
     *
     * @param flPtr 实例对象
     * @return 实例对象
     */
    @PostMapping("update")
    public ResultData update(@RequestBody FlPtr flPtr, HttpServletRequest request) {
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            flPtr.setOrgId(user.getBaseOrgId());
            flPtr.setUpdaterId(user.getId());
            flPtr.setUpdaterName(user.getName());
            flPtr.setCreateTime(new Date());
            flPtr=this.flPtrService.update(flPtr);
            if(flPtr!=null)
            {
                result.setSuccess(true);
                result.setData(flPtr);
            }else {
                result.setSuccess(false);
                result.setErrorMsg("修改失败");
            }
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @PostMapping("deleteById")
    public ResultData deleteById(Integer id, HttpServletRequest request) {
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            FlPtr flPtr=this.flPtrService.queryById(id);
            if(flPtr==null){
                result.setSuccess(false);
                result.setData("未查询到数据");
                return result;
            }
            flPtr.setOrgId(user.getBaseOrgId());
            flPtr.setUpdaterId(user.getId());
            flPtr.setUpdaterName(user.getName());
            flPtr.setCreateTime(new Date());
            flPtr.setDelSign(1);
            flPtr=this.flPtrService.update(flPtr);
            if(flPtr!=null)
            {
                result.setSuccess(true);
                result.setData(flPtr);
            }else {
                result.setSuccess(false);
                result.setErrorMsg("修改失败");
            }
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }


    /**
     * 通过实体作为筛选条件查询
     *
     * @param flPtr 实例对象
     * @return 对象列表
     */
    @PostMapping("queryAll")
    public ResultData queryAll( @RequestBody FlPtr flPtr, HttpServletRequest request) {
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            flPtr.setDelSign(0);
            PageInfo<FlPtr> list=this.flPtrService.queryAll(flPtr);
            if(flPtr!=null)
            {
                result.setSuccess(true);
                result.setData(list);
            }else {
                result.setSuccess(false);
                result.setErrorMsg("修改失败");
            }
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }

    /**
     * 导出EXECL文件
     * @param response
     * @param name
     */
    @GetMapping("/downloadFile")
    @ResponseBody
    public void downloadFile(HttpServletResponse response, String ids,String yearTiem,String orgId) {

        SimpleDateFormat formatYYYY = new SimpleDateFormat("YYYYMMdd");
        String fileName ="";
        Map<String,Object> map1 = new HashMap<String, Object>() ;
        String filePath = "";
        fileName="人员调动_"+formatYYYY.format(new Date())+".xlsx";
        filePath = "templates/PTRVo.xlsx";
        //导出数据
        List<FlPtr> list1=new ArrayList<>();

        if(ids!=null){
            String[] idss=ids.split(",");
            for(int i=0;i<idss.length;i++){
                list1.add(this.flPtrService.queryById(Integer.valueOf(idss[i])));
            }
        }else {
            FlPtr flPtr=new FlPtr();
            flPtr.setPage(1);
            flPtr.setPageSize(100000);
            if(yearTiem!=null){
                flPtr.setDdtime(yearTiem);
            }
           if(orgId!=null){
               flPtr.setYdwmcId(orgId);
           }
           PageInfo<FlPtr> pageInfo=this.flPtrService.queryAll(flPtr);
            list1=pageInfo.getList();
        }

        map1.put("list",list1);
        try{
            // 获取导出excel指定模版
            System.out.println("生成模板文件");
            //获取项目的根目录
            String rootPath = System.getProperty("user.dir");
            //创建临时的模板存放文件
            String path = rootPath +"/" +filePath;
            System.out.println("存放模板目录及模板文件：："+path);
            File file = new File(path);
            if(!file.exists()){
                System.out.println("不存在则创建文件："+path);
                ClassPathResource resource = new ClassPathResource(filePath);
                InputStream inputStream = resource.getInputStream();
                saveTempFile(inputStream,file);
                System.out.println("模板创建成功!");
            }
            TemplateExportParams params = new TemplateExportParams(path,true);
            // 导出excel
            System.out.println("生产execl");
            // 存放数据map


            Workbook workbook= ExcelExportUtil.exportExcel(params , map1 );
            downLoadExcel(fileName,response,workbook);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private static void saveTempFile(InputStream inputStream, File tempFile) throws IOException {
        //如果文件的目录不存在
        if(!tempFile.getParentFile().exists()){
            //创建父目录
            tempFile.getParentFile().mkdirs();
        }
        OutputStream os = new FileOutputStream(tempFile);
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }
        os.flush();
        os.close();
        inputStream.close();
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            // 指定下载的文件名--设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
